package com.asd.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.asd.common.Result;
import com.asd.map.entity.Information;
import com.asd.map.entity.Map_apply;
import com.asd.map.service.ApplyService;
import com.asd.map.service.IInformationService;
import com.asd.system.entity.Organization;
import com.asd.system.entity.User;
import com.asd.system.entity.UserQuery;
import com.asd.system.entity.UserRole;
import com.asd.system.service.IUserRoleService;
import com.asd.system.service.IUserService;
import com.asd.system.service.OrganizationService;
import com.asd.system.entity.vo.UserRoleVO;
import com.asd.util.MD5Util;
import com.asd.util.PasswordUtil;
import com.asd.util.RedisUtil;
import com.asd.util.oConvertUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author
 * @createtime 2021-09-13 14:18
 * @description
 */
@Api(tags = "用户Api")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private ApplyService applyService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IInformationService informationService;

    @Autowired
    private OrganizationService organizationService;

    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "用户-分页列表查询", notes = "用户-分页列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小")
    })
    @GetMapping(value = "/list")
    public Result<?> queryPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "2") Integer pageSize) {
        Page<User> page = new Page<User>(pageNo, pageSize);

        List<User> list = userService.selectUserPage(page);

        Page<User> pageList = page.setRecords(list);

        return Result.ok(pageList);
    }

    /**
     * 修改昵称
     *
     * @param
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true),
            @ApiImplicitParam(name = "nickname", value = "昵称")
    })
    @ApiOperation(value = "用户-修改昵称", notes = "用户-修改昵称")
    @PutMapping(value = "/updateFornickname")
    public Result<?> edit(@RequestParam("id") String id, @RequestParam("nickname") String nickname) {


        User user1 = userService.getById(id);


        if (!(nickname.equals(null) || nickname.equals(""))) {
            user1.setNickname(nickname);
        }

        userService.updateById(user1);
        return Result.ok("修改昵称成功!");
    }

//
//    /**
//     * 修改用户状态
//     *
//     * @param
//     * @return
//     */
//    @ApiOperation(value = "用户-修改用户状态", notes = "用户-修改用户状态")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userName", value = "用户名", required = true),
//            @ApiImplicitParam(name = "isEnable", value = "账号是否启用(0:冻结,1:启用)")
//    })
//    @PutMapping(value = "/update")
//    public Result<?> edit1(@RequestParam("userName") String userName, @RequestParam("isEnable") String isEnable) {
//
//        Result<JSONObject> result = new Result<JSONObject>();
//
//        User user = userService.findToName(userName);
//        String userIsEnable = user.getIsEnable();
//
//        //修改账号状态
//        if (!(isEnable.equals(null) || isEnable.equals(""))) {
//
//            if (userIsEnable.equals("1") && isEnable.equals("1")) {
//                result.setMessage("该用户已激活,无需再次激活！");
//            } else {
//                user.setIsEnable(isEnable);
//                userService.updateById(user);
//                result.setMessage("用户状态修改成功！");
//            }
//        }
//        return result;
//    }


    /**
     * 用户-修改
     */
    @ApiOperation(value = "用户-修改", notes = "用户-修改")
    @PutMapping("/update")
    public Result<?> update(@RequestBody User user) {
        userService.updateById(user);

        return Result.ok("修改成功");
    }


    @ApiOperation(value = "用户注册", notes = "用户注册")
    @PutMapping("/regist1")
    public Result<?> regist(@RequestParam("userName") String userName,
                            @RequestParam("passWord") String passWord) {

        Result<JSONObject> result = new Result<JSONObject>();

        //注册逻辑函数
        User userExist = userService.findToName(userName);
        //判断用户名
        if (userName.equals("")) {
            return Result.error("用户名或密码不能为空!");
            //判断用户密码
        } else if (passWord.equals("")) {
            return Result.error("用户名或密码不能为空!");
        } else if (userExist != null) {
            return Result.error("用户名或密码已存在!");
        }

        try {
            //随机获取密码加密的 盐值salt
            String salt = oConvertUtils.randomGen(8);
            //对用户输入的密码进行加密处理
            String passwordEncode = PasswordUtil.encrypt(userName, passWord, salt);
            User user = new User();
            user.setSalt(salt);
            user.setUserName(userName);
            //新增用户时默认用户状态为冻结
            user.setIsEnable("0");
            user.setPassWord(passwordEncode);
            userService.save(user);
            result.success("注册成功");
        } catch (Exception e) {
            result.error500("注册失败");
        }
        return result;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", required = true),
            @ApiImplicitParam(name = "passWord", value = "密码", required = true),
            @ApiImplicitParam(name = "captcha", value = "验证码", required = true),
            @ApiImplicitParam(name = "nickname", value = "昵称"),
            @ApiImplicitParam(name = "checkKey", value = "验证码key", required = true)
    })
    @ApiOperation(value = "带验证码用户注册", notes = "带验证码用户注册")
    @PutMapping("/regist")
    public Result<?> regist1(@RequestParam("userName") String userName,
                             @RequestParam("passWord") String passWord,
                             @RequestParam("captcha") String captcha,
                             @RequestParam("nickname") String nickname,
                             @RequestParam("checkKey") String checkKey) {

        Result<JSONObject> result = new Result<JSONObject>();

        //校验验证码
//        Boolean sucess_login = (Boolean)redisUtil.get("sucess_login");
//        if(sucess_login != null && !sucess_login) {
        if (captcha == null) {
            result.error500("验证码无效!");
            return result;
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = MD5Util.MD5Encode(lowerCaseCaptcha + checkKey, "utf-8");

        Object checkCode = redisUtil.get(realKey);


        if (checkCode == null || !checkCode.equals(lowerCaseCaptcha)) {
            result.error500("验证码错误!");
            return result;
        }
//        }

        //注册逻辑函数
        User userExist = userService.findToName(userName);
        //判断用户名
        if (userName.equals("")) {
            return Result.error("用户名或密码不能为空!");
            //判断用户密码
        } else if (passWord.equals("")) {
            return Result.error("用户名或密码不能为空!");
        } else if (userExist != null) {
            return Result.error("用户名或密码已存在!");
        }


        try {
            //随机获取密码加密的 盐值salt
            String salt = oConvertUtils.randomGen(8);
            //对用户输入的密码进行加密处理
            String passwordEncode = PasswordUtil.encrypt(userName, passWord, salt);
            User user = new User();
            user.setSalt(salt);
            user.setUserName(userName);
            //新增用户时默认用户状态为冻结
            user.setIsEnable("0");
            user.setPassWord(passwordEncode);
            //设置昵称
            user.setNickname(nickname);

            userService.save(user);
            result.success("注册成功!");
        } catch (Exception e) {
            result.error500("注册失败!");
        }
        return result;
    }


    /**
     * 用户更改密码
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", required = true),
            @ApiImplicitParam(name = "passWord", value = "密码", required = true),
            @ApiImplicitParam(name = "oldPassword", value = "原密码", required = true)
    })
    @ApiOperation(value = "用户-用户更改密码", notes = "用户-用户更改密码")
    @GetMapping("/passwordChange")
    public Result<User> passwordChange(@RequestParam(name = "userName") String userName,
                                       @RequestParam(name = "passWord") String passWord,
                                       @RequestParam(name = "oldPassword") String oldPassword) {


        Result<User> result = new Result<User>();
        if (oConvertUtils.isEmpty(userName) || oConvertUtils.isEmpty(passWord) || oConvertUtils.isEmpty(oldPassword)) {
            result.setMessage("重置密码失败！");
            result.setSuccess(false);
            return result;
        }

        if (passWord.equals(oldPassword)) {
            result.setMessage("新密码不能与原密码一致！");
            result.setSuccess(false);
            return result;
        }


        User user = new User();

        user = this.userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, userName));
        if (user == null) {
            result.setMessage("未找到用户！");
            result.setSuccess(false);
            return result;
        } else {
            User user1 = userService.findToName(userName);
            String OldPassWord1 = user1.getPassWord();
            String salt1 = user1.getSalt();
            String passwordEncode1 = PasswordUtil.encrypt(user1.getUserName(), passWord, salt1);
            if (OldPassWord1.equals(passwordEncode1)) {
                result.setMessage("原密码不正确!");
                result.setSuccess(false);
                return result;
            } else {
                String salt = oConvertUtils.randomGen(8);
                user.setSalt(salt);
                String passwordEncode = PasswordUtil.encrypt(user.getUserName(), passWord, salt);
                user.setPassWord(passwordEncode);
                this.userService.updateById(user);
                result.setSuccess(true);
                result.setMessage("修改密码成功！");
                return result;
            }
        }
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "用户-通过id删除", notes = "用户-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
//        System.out.println("id=====" + id);

        userService.removeById(id);

        return Result.ok("删除成功!");
    }

    /**
     * 批量删除用户
     */
    @ApiOperation(value = "用户-批量删除用户", notes = "用户-批量删除用户")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.userService.deleteBatchUsers(ids);
        return Result.ok("批量删除用户成功");
    }


    @ApiOperation(value = "用户-根据id查询", notes = "用户-根据id查询")
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<User> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<User> result = new Result<User>();
        User user = userService.getById(id);
        if (user == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(user);
            result.setSuccess(true);
        }
        return result;
    }


    @ApiOperation(value = "用户-查询用户角色", notes = "用户-查询用户角色")
    @RequestMapping(value = "/queryUserRole", method = RequestMethod.GET)
    public Result<List<String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {
        Result<List<String>> result = new Result<>();
        List<String> list = new ArrayList<String>();
        List<UserRole> userRole = userRoleService.list(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, userid));
        if (userRole == null || userRole.size() <= 0) {
            result.error500("未找到用户相关角色信息");
        } else {
            for (UserRole userRole1 : userRole) {
                list.add(userRole1.getRoleId());
            }
            result.setSuccess(true);
            result.setResult(list);
        }
        return result;
    }


    /**
     * @param userIds
     * @return
     * @功能：根据id 批量查询
     */
    @ApiOperation(value = "用户-批量查询", notes = "用户-批量查询")
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public Result<Collection<User>> queryByIds(@RequestParam String userIds) {
        Result<Collection<User>> result = new Result<>();
        String[] userId = userIds.split(",");
        Collection<String> idList = Arrays.asList(userId);
        Collection<User> userRole = userService.listByIds(idList);
        result.setSuccess(true);
        result.setResult(userRole);
        return result;
    }


//    /**
//     * 给指定角色添加用户(存在中间表时)
//     *
//     * @param
//     * @return
//     */
//    @ApiOperation(value = "给指定角色添加用户", notes = "给指定角色添加用户")
//    @RequestMapping(value = "/addUserRole1", method = RequestMethod.POST)
//    public Result<String> addUserRole1(@RequestBody UserRoleVO userRoleVO) {
//        Result<String> result = new Result<String>();
//        try {
//            String roleId = userRoleVO.getRoleId();
//            for (String userId : userRoleVO.getUserIdList()) {
//
//                UserRole userRole = new UserRole();
//                userRole.setRoleId(roleId);
//                userRole.setUserId(userId);
//
//                QueryWrapper<UserRole> queryWrapper = new QueryWrapper<UserRole>();
//                queryWrapper.eq("roleId", roleId).eq("userId", userId);
//                UserRole one = userRoleService.getOne(queryWrapper);
//                if (one == null) {
//                    userRoleService.save(userRole);
//                }
//
//            }
//            result.setMessage("添加成功!");
//            result.setSuccess(true);
//            return result;
//        } catch (Exception e) {
//            result.setSuccess(false);
//            result.setMessage("出错了: " + e.getMessage());
//            return result;
//        }
//    }

//    /**
//     * 删除指定角色的用户关系(存在中间表时)
//     *
//     * @param
//     * @return
//     */
//    @ApiOperation(value = "删除指定角色的用户关系", notes = "删除指定角色的用户关系")
//    @RequestMapping(value = "/deleteUserRole", method = RequestMethod.DELETE)
//    public Result<UserRole> deleteUserRole(@RequestParam(name = "roleId") String roleId,
//                                           @RequestParam(name = "userId", required = true) String userId
//    ) {
//        Result<UserRole> result = new Result<UserRole>();
//        try {
//            QueryWrapper<UserRole> queryWrapper = new QueryWrapper<UserRole>();
//            queryWrapper.eq("roleId", roleId).eq("userId", userId);
//            userRoleService.remove(queryWrapper);
//            result.success("删除成功!");
//        } catch (Exception e) {
//            result.error500("删除失败！");
//        }
//        return result;
//    }

    /**
     * 给指定角色添加用户(不存在中间表时)
     *
     * @param
     * @return
     */
    @ApiOperation(value = "给指定角色添加用户", notes = "给指定角色添加用户")
    @RequestMapping(value = "/addUserRole", method = RequestMethod.POST)
    public Result<String> addUserRole(@RequestBody UserRoleVO userRoleVO) {
        Result<String> result = new Result<String>();
        try {
            String roleId = userRoleVO.getRoleId();
            for (String userId : userRoleVO.getUserIdList()) {
                User user = userService.getById(userId);
                if (user == null) {
                    result.error500("未找到对应用户");
                } else {
                    user.setRoleId(roleId);
                    userService.updateById(user);
                }
            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }
    /**
     * 删除指定角色的用户关系(不存在中间表时)
     *
     * @param
     * @return
     */
    @ApiOperation(value = "删除指定角色的用户关系", notes = "删除指定角色的用户关系")
    @RequestMapping(value = "/deleteUserRole", method = RequestMethod.DELETE)
    public Result<UserRole> deleteUserRole(@RequestParam(name = "roleId") String roleId,
                                           @RequestParam(name = "userId", required = true) String userId) {
        Result<UserRole> result = new Result<UserRole>();
        try {
            User user = userService.getById(userId);
            user.setRoleId("");
            userService.updateById(user);
            result.success("删除成功!");
        } catch (Exception e) {
            result.error500("删除失败！");
        }
        return result;
    }



    /**
     * 批量删除指定角色的用户关系
     *
     * @param
     * @return
     */
    @ApiOperation(value = "批量删除指定角色的用户关系", notes = "批量删除指定角色的用户关系")
    @RequestMapping(value = "/deleteUserRoleBatch", method = RequestMethod.DELETE)
    public Result<UserRole> deleteUserRoleBatch(
            @RequestParam(name = "roleId") String roleId,
            @RequestParam(name = "userIds", required = true) String userIds) {
        Result<UserRole> result = new Result<UserRole>();
        try {
            QueryWrapper<UserRole> queryWrapper = new QueryWrapper<UserRole>();
            queryWrapper.eq("roleId", roleId).in("userId", Arrays.asList(userIds.split(",")));
            userRoleService.remove(queryWrapper);
            result.success("删除成功!");
        } catch (Exception e) {
            result.error500("删除失败！");
        }
        return result;
    }


    @ApiOperation(value = "用户-查询全部已激活未指定角色用户", notes = "用户-查询全部已激活未指定角色用户")
    @RequestMapping(value = "/queryall", method = RequestMethod.GET)
    public Result<List<User>> queryall() {
        Result<List<User>> result = new Result<>();
        List<User> list = userService.list();
        List<User> userList = new ArrayList<>();
        if (list == null || list.size() <= 0) {
            result.error500("未找到用户信息");
        } else {

            for (int i = 0; i < list.size(); i++) {
                User user = list.get(i);
                if (user.getIsEnable().equals("1")) {//判断该用户已激活
                    UserRole userRole = userRoleService.findByUserId(user.getId());
                    if (userRole == null) {//判断该用户未指定角色
                        userList.add(user);
                    }
                }
            }
            result.setResult(userList);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 查询用户信息和所属应用以及数据源
     */
    @ApiOperation(value = "用户信息-通过登录账号查询", notes = "用户信息-通过登录账号查询")
    @GetMapping(value = "/query")
    public Result<?> query(@RequestParam(name = "username", required = true) String username) {
        //定义返回的对象
        UserQuery userQuery = new UserQuery();
        //定义一个应用集合
        ArrayList appList = new ArrayList<Map_apply>();
        //定义一个应用集合
        ArrayList infList = new ArrayList<Information>();
        //获取用户信息
        User user = userService.findToName(username);
        String id = user.getId();
        String userName = user.getUserName();
        String isEnable = user.getIsEnable();
        String orgId = user.getOrgId();
        //权限id,0\1\2,直接传给前端进行判断，不需要查询权限名称
        String roleId = user.getRoleId();
        //通过id获取组织名称
        Organization org = organizationService.getById(orgId);
        String orgName = org.getName();

        //获取应用集合
        String dataApp = user.getDataApp();
        //获取数据源集合
        String dataInf = user.getDataInf();
        //判断应用字段是否为空
        if (!(dataApp.equals(null) || dataApp.equals(""))) {
            //将字符串转换为数组
            JSONArray array = JSONObject.parseArray(dataApp);

            for (int i = 0; i < array.size(); i++) {
                Map_apply apply = new Map_apply();
                String appId = array.getString(i);
                apply = applyService.getById(appId);
                appList.add(apply);
            }

        }
        //判断数据源字段是否为空
        if (!(dataInf.equals(null) || dataInf.equals(""))) {
            //将字符串转换为数组
            JSONArray array1 = JSONObject.parseArray(dataInf);

            for (int i = 0; i < array1.size(); i++) {
                Information information = new Information();
                String infId = array1.getString(i);
                information = informationService.getById(infId);
                infList.add(information);
            }

        }
        //将获取到的而数据分装到实体中进行返回
        userQuery.setId(id);
        userQuery.setOrgName(orgName);
        userQuery.setOrgId(orgId);
        userQuery.setRoleId(roleId);
        userQuery.setUserName(userName);
        userQuery.setIsEnable(isEnable);
        userQuery.setApplyList(appList);
        userQuery.setInformationList(infList);


        return Result.ok(userQuery);
    }


    /**
     * 修改用户基本信息
     */
    @ApiOperation(value = "用户-修改用户基本信息", notes = "用户-修改用户基本信息")
    @PutMapping("/updateUserBasicInfo")
    public Result<?> updateUserBasicInfo(@RequestParam("id") String id, @RequestParam("nickname") String nickname,@RequestParam("note")  String note) {

        Result<User> result = new Result<User>();

        User user = userService.getById(id);
        if (user == null) {
            result.error500("未找到对应组织");
        } else {
            boolean ok = userService.updateUserBasicInfo(id, nickname, note);

            if (ok) {
                result.success("修改成功!");
            }

        }
        return result;
    }


}
